package com.wt.hystrix.integration;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

/**
 * @Description
 * @Author: wangtao
 * @Date:13:40 2017/6/6
 * @Email:tao8.wang@changhong.com
 */
@Service
public class TimeOutStoreService {

    @HystrixCommand(fallbackMethod = "defaultStores", commandProperties =
            {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
                    value = "1000")})
    public Object getStores(Map<String, Object> parameters) {
        hystrixRadomError("getStores", "defaultStores");
        return "getStores";
    }

    @HystrixCommand(fallbackMethod = "mydefaultStores", commandProperties =
            {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
                    value = "5000")})
    public Object defaultStores(Map<String, Object> parameters) {
        delay();
        return "getStore--->defaultStores";
    }

    public Object mydefaultStores(Map<String, Object> parameters) {
        return "getStore--->defaultStores--->mydefaultStores";
    }

    //进入死循环，让请求超时，进入断路器
    private void delay() {
        int i = 0;
        while (true)
            System.out.println("delay" + i++);
    }

    private void hystrixRadomError(String currentMthodName, String nextMethodName) {
        Random random = new Random();
        int i = random.nextInt(10);
        if (i <= 5)
            //i<=5的时候正常
            System.out.println(currentMthodName + ";i=" + i + ";" + currentMthodName + "断路器未工作");
        else {
            //其他情况下，让其出错，执行断路器指定的方法
            System.out.println(currentMthodName + ";i=" + i + ";" + currentMthodName + "断路器开始工作,执行断路器指定的方法：" + nextMethodName);
            i = 1 / 0;
        }
    }

}
